package ReflectStudy.Exa7;

import java.lang.reflect.Field;

/**
 * 利用反射设置对象的字段值(包括私有的)
 */
public class Test {

    public static void main(String[] args) {
        Student student = new Student();
        Student.Body body = new Student.Body();
        body.setClientNo("000001");
        body.setLoanNo("132342353423r");
        student.body = body;
        student.setId(8);
        student.setAccount(20);
        student.setMale(true);
        student.setName("麻子");
        //获得得student对象的Class对象
        Class<?> clazz = student.getClass();
        System.out.println("类的标准名称：" + clazz.getCanonicalName());
        try {
            //得到对象中名为id的字段对象
            Field id = clazz.getDeclaredField("id");
            System.out.println("nameFileName: " + id.getName());
            System.out.println("设置前的id：" + student.getId());
            id.setAccessible(true);
            id.setInt(student, 10);// 设置Id值为10
            System.out.println("设置后的id：" + student.getId());

            Field name = clazz.getDeclaredField("name");
            System.out.println("nameFileName: " + name.getName());
            System.out.println("设置前的name：" + student.getName());
            name.setAccessible(true);
            name.set(student, "四郎");// 设置name值为明日科技
            System.out.println("设置后的name：" + student.getName());

            Field male = clazz.getDeclaredField("male");
            System.out.println("设置前的male：" + student.isMale());
            male.setAccessible(true);
            male.setBoolean(student, false);// 设置male值为true
            System.out.println("设置后的male：" + student.isMale());

            Field account = clazz.getDeclaredField("account");
            System.out.println("设置前的account：" + student.getAccount());
            account.setDouble(student, 45.67);// 设置account值为12.34
            System.out.println("设置后的account：" + student.getAccount());
        } catch (SecurityException | NoSuchFieldException | IllegalArgumentException | IllegalAccessException e) {
            e.printStackTrace();
        }
    }

}
